package com.example.a_java.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * JSON类型处理器，用于Map或List类型与JSON字符串的相互转换
 * 修改为使用全局配置的ObjectMapper，确保字符编码一致
 */
@MappedTypes({Map.class, List.class})
@Component
public class JsonTypeHandler extends BaseTypeHandler<Object> {

    private static final Logger logger = LoggerFactory.getLogger(JsonTypeHandler.class);
    
    private static ObjectMapper objectMapper;
    
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        JsonTypeHandler.objectMapper = objectMapper;
    }
    
    // 初始值，在注入前使用
    private static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        try {
            ObjectMapper mapper = objectMapper != null ? objectMapper : DEFAULT_MAPPER;
            String json = mapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            logger.error("转换JSON失败", e);
            throw new SQLException("转换JSON失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parse(rs.getString(columnName));
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parse(rs.getString(columnIndex));
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parse(cs.getString(columnIndex));
    }

    /**
     * 解析JSON字符串为对象
     *
     * @param json JSON字符串
     * @return 解析后的对象
     */
    private Object parse(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        
        try {
            ObjectMapper mapper = objectMapper != null ? objectMapper : DEFAULT_MAPPER;
            
            // 确保字符串编码正确
            byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
            String validJson = new String(bytes, StandardCharsets.UTF_8);
            
            if (validJson.startsWith("{")) {
                return mapper.readValue(validJson, Map.class);
            } else if (validJson.startsWith("[")) {
                return mapper.readValue(validJson, List.class);
            } else {
                return validJson;
            }
        } catch (JsonProcessingException e) {
            logger.error("解析JSON失败", e);
            return null;
        }
    }
} 
